package com.lottery.server.controller;

import com.lottery.server.common.JsonResult;
import com.lottery.server.common.ResultCode;
import com.lottery.server.common.exception.BusinessException;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/api/lottery/file")
public class FileController {
    @Value("${file.upload.base-path:/srv}")
    private String basePath;

    @PostMapping("/upload")
    public JsonResult<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new BusinessException(ResultCode.VALIDATE_FAILED, "请选择要上传的文件");
        }

        try {
            // 生成日期目录
            String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
            String uploadDir = basePath + "/" + dateDir;

            // 创建目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String filename = UUID.randomUUID().toString() + extension;

            // 保存文件
            File dest = new File(uploadDir + "/" + filename);
            file.transferTo(dest);

            // 返回相对路径
            String relativePath = "/srv/upload/" + dateDir + "/" + filename;

            return JsonResult.success(relativePath);
        } catch (IOException e) {
            throw new BusinessException(ResultCode.ERROR, "文件上传失败：" + e.getMessage());
        }
    }
} 